<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>






<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="iOS,Android," />





  <link rel="alternate" href="/atom.xml" title="Bingo's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="关于 Objective-C 的编码规范，苹果和谷歌都已经有很好的总结：  Apple Coding Guidelines for Cocoa Google Objective-C Style Guide  但每个公司都有自己的规范，蛋壳也不例外，以下是蛋壳 iOS 部门的OC编码规范。">
<meta name="keywords" content="iOS,Android">
<meta property="og:type" content="article">
<meta property="og:title" content="iOS开发编码规范">
<meta property="og:url" content="https://bingozb.github.io/27.html">
<meta property="og:site_name" content="Bingo's Blog">
<meta property="og:description" content="关于 Objective-C 的编码规范，苹果和谷歌都已经有很好的总结：  Apple Coding Guidelines for Cocoa Google Objective-C Style Guide  但每个公司都有自己的规范，蛋壳也不例外，以下是蛋壳 iOS 部门的OC编码规范。">
<meta property="og:updated_time" content="2017-04-20T12:33:34.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="iOS开发编码规范">
<meta name="twitter:description" content="关于 Objective-C 的编码规范，苹果和谷歌都已经有很好的总结：  Apple Coding Guidelines for Cocoa Google Objective-C Style Guide  但每个公司都有自己的规范，蛋壳也不例外，以下是蛋壳 iOS 部门的OC编码规范。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: 'JE30EVH7NI',
      apiKey: '862bb3deb9a3166ed99de0be6527f59c',
      indexName: 'blog',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键词进行搜索","hits_empty":"找不到关于「 ${query} 」的文章","hits_stats":"共找到 ${hits} 篇文章，花了 ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://bingozb.github.io/27.html"/>





  <title>iOS开发编码规范 | Bingo's Blog</title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?c8a59b9753bce3ec58f81c89e2acce96";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Bingo's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Stay Hungry, Stay Foolish.</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocapitalize="off" autocomplete="off" autocorrect="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://bingozb.github.io/27.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Bingo">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Bingo's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                iOS开发编码规范
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-03-03T16:56:26+08:00">
                2017-03-03
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/工作总结/" itemprop="url" rel="index">
                    <span itemprop="name">工作总结</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/27.html#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="27.html" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          
             <span id="/27.html" class="leancloud_visitors" data-flag-title="iOS开发编码规范">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>关于 Objective-C 的编码规范，苹果和谷歌都已经有很好的总结：</p>
<ul>
<li><a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html" target="_blank" rel="external">Apple Coding Guidelines for Cocoa</a></li>
<li><a href="https://google-styleguide.googlecode.com/svn/trunk/objcguide.xml?showone=Line_Length#Line_Length" target="_blank" rel="external">Google Objective-C Style Guide</a></li>
</ul>
<p>但每个公司都有自己的规范，蛋壳也不例外，以下是蛋壳 iOS 部门的OC编码规范。</p>
<a id="more"></a>
<h2 id="代码规范"><a href="#代码规范" class="headerlink" title="代码规范"></a>代码规范</h2><h3 id="头文件"><a href="#头文件" class="headerlink" title="头文件"></a>头文件</h3><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"></div><div class="line">头文件</div><div class="line"></div><div class="line">全局宏</div><div class="line"></div><div class="line">常量定义</div><div class="line"></div><div class="line">全局变量</div><div class="line"></div><div class="line">类定义</div></pre></td></tr></table></figure>
<p>头文件切记不要 <code>#import &lt;AVFoundation/AVFoundation.h&gt;</code>，在 iOS7 以后推荐用 <code>@import module;</code> 来引用苹果的组件。</p>
<figure class="highlight clean"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">@<span class="keyword">import</span> AVFoundation; # 标准组件库库头文件，一般为苹果sdk自带的 framework</div><div class="line">#<span class="keyword">import</span> DKViewController.h # 非标准库头文件</div></pre></td></tr></table></figure>
<p><strong>例子</strong></p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">@import</span> <span class="built_in">AVFoundation</span>;</div><div class="line"><span class="meta">#import <span class="meta-string">"Test.h"</span></span></div><div class="line"></div><div class="line"><span class="meta">#define KTest 0</span></div><div class="line"></div><div class="line"><span class="keyword">static</span> <span class="built_in">CGFloat</span> <span class="keyword">const</span> kALAnimationDelay = <span class="number">0.1</span>;</div><div class="line"><span class="keyword">static</span> <span class="built_in">NSString</span> *ID = <span class="string">@"cell"</span>;</div><div class="line"></div><div class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">MyClass</span> ()</span></div><div class="line"></div><div class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>) <span class="built_in">NSObject</span> *test;</div><div class="line"></div><div class="line"><span class="keyword">@end</span></div></pre></td></tr></table></figure>
<h3 id="类结构"><a href="#类结构" class="headerlink" title="类结构"></a>类结构</h3><p>使用 #pragma mark – xxx 来分类方法</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="meta">#pragma mark – Getters and Setters # 懒加载</span></div><div class="line"> </div><div class="line"><span class="meta">#pragma mark - Life Cycle # 实例生命周期</span></div><div class="line"></div><div class="line"><span class="meta">#pragma mark - Events # 事件</span></div><div class="line"></div><div class="line"><span class="meta">#pragma mark - Public Methods # .h 公开方法</span></div><div class="line"></div><div class="line"><span class="meta">#pragma mark - UITableViewDataSource # 系统代理方法</span></div><div class="line"><span class="meta">#pragma mark - UITableViewDelegate</span></div><div class="line"><span class="meta">#pragma mark - UITextFieldDelegate</span></div><div class="line"></div><div class="line"><span class="meta">#pragma mark - Custom Delegates # 自定义代理</span></div><div class="line"></div><div class="line">(<span class="meta">#pragma mark – Private Methods # 私有方法)</span></div></pre></td></tr></table></figure>
<h3 id="Private-Methods"><a href="#Private-Methods" class="headerlink" title="Private Methods"></a>Private Methods</h3><ul>
<li><p>不是 delegate 方法的，也不是 event response 方法的，也不是 life cycle 方法的，就是 private method。</p>
</li>
<li><p>正常情况下 ViewController 里面是不会存在 private methods 的，这个 private methods 一般是用于日期换算、图片裁剪等的小功能。这种小功能要么把它写成一个 category，要么把它做成一个模块，哪怕这个模块只有一个函数也行。</p>
</li>
<li><p>ViewController 基本上是大部分业务的载体，本身代码已经相当复杂，所以跟业务关联不大的东西，能不放在 ViewController 里面就不要放。另外一点，这个 private method 的功能这时候只是你用得到，但是将来说不定别的地方也会用到，一开始就独立出来，有利于将来的代码复用。</p>
</li>
</ul>
<h3 id="懒加载"><a href="#懒加载" class="headerlink" title="懒加载"></a>懒加载</h3><p>很多开发工程师，初始化属性的位置比较随意，有单独添加一个初始化方法类似 setupView 的，有在 init 初始化的，各种情况都有，导致团队协作的时候代码显得非常乱。</p>
<p>初始化方式不一致，这样做非常有可能破坏了每个方法功能的单一性（每个方法只做一件事）。</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">CustomObject</span> ()</span></div><div class="line"></div><div class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>, <span class="keyword">strong</span>) <span class="built_in">UILabel</span> *label;</div><div class="line"></div><div class="line"><span class="keyword">@end</span></div><div class="line"></div><div class="line"><span class="class"><span class="keyword">@implementation</span></span></div><div class="line"></div><div class="line"><span class="meta">#pragma mark - getters and setters</span></div><div class="line"></div><div class="line">- (<span class="built_in">UILabel</span> *)label </div><div class="line">&#123;</div><div class="line">    <span class="keyword">if</span> (_label == <span class="literal">nil</span>) &#123;</div><div class="line">        _label = [[<span class="built_in">UILabel</span> alloc] init];</div><div class="line">        _label.text = <span class="string">@"1234"</span>;</div><div class="line">        _label.font = [<span class="built_in">UIFont</span> systemFontOfSize:<span class="number">12</span>];</div><div class="line">        ... ...</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> _label;</div><div class="line">&#125;</div><div class="line"><span class="keyword">@end</span></div><div class="line"> </div><div class="line"><span class="meta">#pragma mark - life cycle</span></div><div class="line"></div><div class="line">- (<span class="keyword">void</span>)viewDidLoad </div><div class="line">&#123;</div><div class="line">    [<span class="keyword">super</span> viewDidLoad];</div><div class="line">    [<span class="keyword">self</span>.view addSubview:<span class="keyword">self</span>.label];</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (<span class="keyword">void</span>)viewWillAppear:(<span class="built_in">BOOL</span>)animated </div><div class="line">&#123;</div><div class="line">    [<span class="keyword">super</span> viewWillAppear:animated];</div><div class="line">    <span class="keyword">self</span>.label.frame = <span class="built_in">CGRectMake</span>(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="空格"><a href="#空格" class="headerlink" title="空格"></a>空格</h3><p>不要在工程里使用 Tab 键，使用空格来进行缩进。在 Xcode &gt; Preferences &gt; Text Editing 将 Tab 和自动缩进都设置为4个空格。（Google 的标准是使用两个空格来缩进，但这里还是推荐使用 Xcode 默认的设置。）</p>
<p>每个方法或者功能块之间为了结构清晰，应当只空一行。</p>
<p>该空格的地方要加空格，比如每个方法的开头，在 - 和 (return_type) 之间应该有且只有一个空格；写 property 时，严格按照下面的格式。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">SomeClass</span> : <span class="title">NSObject</span></span></div><div class="line"></div><div class="line"><span class="keyword">@property</span> (noatomic, <span class="keyword">weak</span>) <span class="built_in">UIView</span> *aView</div><div class="line"></div><div class="line">- (<span class="keyword">void</span>)someMethod;</div><div class="line"></div><div class="line"><span class="keyword">@end</span></div><div class="line"></div><div class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">SomeClass</span></span></div><div class="line"></div><div class="line">- (<span class="keyword">void</span>)setAView:(<span class="built_in">NSInteger</span> )aview </div><div class="line">&#123;</div><div class="line"></div><div class="line">&#125;</div><div class="line"></div><div class="line">- (<span class="keyword">void</span>)someMethod </div><div class="line">&#123;</div><div class="line"></div><div class="line">&#125;</div><div class="line"><span class="keyword">@end</span></div></pre></td></tr></table></figure>
<h3 id="方法书写"><a href="#方法书写" class="headerlink" title="方法书写"></a>方法书写</h3><p>先不讨论一个方法带很多参数好不好，假设真的有很多参数导致方法名很长，应该用 : 对齐，每个参数一行，以提高可阅读性。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">id</span>)initWithModel:(IPCModle)model</div><div class="line">        connectType:(IPCConnectType)connectType</div><div class="line">         resolution:(IPCResolution)resolution</div><div class="line">           authName:(<span class="built_in">NSString</span> *)authName</div><div class="line">           password:(<span class="built_in">NSString</span> *)password</div><div class="line">                mac:(<span class="built_in">NSString</span> *)mac</div><div class="line">               azIp:(<span class="built_in">NSString</span> *)az_ip</div><div class="line">              azDns:(<span class="built_in">NSString</span> *)az_dns</div><div class="line">              token:(<span class="built_in">NSString</span> *)token</div><div class="line">              email:(<span class="built_in">NSString</span> *)email</div><div class="line">           delegate:(<span class="keyword">id</span>)delegate;</div></pre></td></tr></table></figure>
<p>反之如果只有两三个参数，就不要这样分行写了，一行解决即可。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">id</span>)initWithAuthName:(<span class="built_in">NSString</span> *)authName password:(<span class="built_in">NSString</span> *)password;</div></pre></td></tr></table></figure>
<h3 id="方法调用"><a href="#方法调用" class="headerlink" title="方法调用"></a>方法调用</h3><p>函数调用不要分行，统一单行写完，让编译器自动换行即可。特别是有 block 嵌套的时候，分行会非常难看。一般写完代码的时候可以用一个小技巧来格式化代码：选中代码，然后先按 <code>Command + Alt + [</code>，再按 <code>Command + Alt + ]</code>。就是把这一段代码往上移一行，再往下移一行，回到原来的样子，但是会经过 xCode 的排版，也就达到格式化代码的效果。</p>
<p>例如用:</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// blocks are easily readable  </span></div><div class="line">[UIView <span class="string">animateWithDuration:</span><span class="number">1.0</span> <span class="string">animations:</span>^&#123;  </div><div class="line">    <span class="comment">// something  </span></div><div class="line">&#125; <span class="string">completion:</span>^(BOOL finished) &#123;  </div><div class="line">    <span class="comment">// something  </span></div><div class="line">&#125;];</div></pre></td></tr></table></figure>
<p>而不是</p>
<figure class="highlight dts"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// colon-aligning makes the block indentation hard to read  </span></div><div class="line"> [UIView animateWithDuration:<span class="number">1.0</span>  </div><div class="line"><span class="symbol">                  animations:</span>^&#123;  </div><div class="line">                      <span class="comment">// something  </span></div><div class="line">                  &#125;  </div><div class="line"><span class="symbol">                  completion:</span>^(BOOL finished) &#123;  </div><div class="line">                      <span class="comment">// something  </span></div><div class="line">                  &#125;];</div></pre></td></tr></table></figure>
<h3 id="if-语句"><a href="#if-语句" class="headerlink" title="if 语句"></a>if 语句</h3><p>表达式大括号和其他大括号（if/else/switch/while 等）总是在同一行语句打开但在新行中关闭。如果没有else 并且括号内只有一行语句，可以和if语句同行，并且不需要括号。</p>
<figure class="highlight ada"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (user.isHappy) &#123; </div><div class="line">    //<span class="keyword">Do</span> something</div><div class="line">&#125; <span class="keyword">else</span> &#123; </div><div class="line">    //<span class="keyword">Do</span> something <span class="keyword">else</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">if</span> (somethingIsBad) <span class="keyword">return</span> something;</div></pre></td></tr></table></figure>
<h3 id="switch-语句"><a href="#switch-语句" class="headerlink" title="switch 语句"></a>switch 语句</h3><p>大括号在 case 语句中并不是必须的，除非编译器强制要求。当一个case语句包含多行代码时，大括号应该加上。</p>
<figure class="highlight mel"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">switch</span> (<span class="keyword">condition</span>) &#123;</div><div class="line">    <span class="keyword">case</span> <span class="number">1</span>:</div><div class="line">        <span class="comment">// ...</span></div><div class="line">        <span class="keyword">break</span>;</div><div class="line">    <span class="keyword">case</span> <span class="number">2</span>: &#123;</div><div class="line">        <span class="comment">// ...</span></div><div class="line">        <span class="comment">// Multi-line example using braces</span></div><div class="line">        <span class="keyword">break</span>;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">case</span> <span class="number">3</span>:</div><div class="line">        <span class="comment">// ...</span></div><div class="line">        <span class="keyword">break</span>;</div><div class="line">    <span class="keyword">default</span>: </div><div class="line">        <span class="comment">// ...</span></div><div class="line">        <span class="keyword">break</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>当在 switch 使用枚举类型时，<code>default</code>是不需要的。例如：</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">RWTLeftMenuTopItemType menuType = RWTLeftMenuTopItemMain;</div><div class="line"><span class="keyword">switch</span> (menuType) &#123;</div><div class="line">    <span class="keyword">case</span> <span class="string">RWTLeftMenuTopItemMain:</span></div><div class="line">        <span class="comment">// ...</span></div><div class="line">        <span class="keyword">break</span>;</div><div class="line">    <span class="keyword">case</span> <span class="string">RWTLeftMenuTopItemShows:</span></div><div class="line">        <span class="comment">// ...</span></div><div class="line">        <span class="keyword">break</span>;</div><div class="line">    <span class="keyword">case</span> <span class="string">RWTLeftMenuTopItemSchedule:</span></div><div class="line">        <span class="comment">// ...</span></div><div class="line">        <span class="keyword">break</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="注释"><a href="#注释" class="headerlink" title="注释"></a>注释</h3><p>代码中尽量少注释，让代码能自我描述。不过当需要注释的时候，能需要清楚地解释某个代码块的含义和作用。注释应当保持最新，如果不必要请删除。</p>
<h3 id="点语法"><a href="#点语法" class="headerlink" title="点语法"></a>点语法</h3><ul>
<li><p>点语法是一种很方便封装访问方法调用的方式。当你使用点语法时，通过使用 getter 或 setter 方法，属性仍然被访问或修改。</p>
</li>
<li><p>点语法应该总是被用来访问和修改属性，因为它使代码更加简洁。[ ] 符号更偏向于用在其它例子。</p>
</li>
</ul>
<p>例如用</p>
<p><code>view.backgroundColor = [UIColor orangeColor];</code></p>
<p>而不是</p>
<p><code>[view setBackgroundColor:[UIColor orangeColor]];</code></p>
<p>当然，也有特例，有些控件直接点语法是无效的，比如 </p>
<p><code>btn.titleLabel.text = @&quot;xxx&quot;;</code></p>
<p>是最容易被坑的，编译器不会告诉你错了，但按钮事件是分状态的，写 [ ] 就可以清楚地看到。正确地赋值语句应该是：</p>
<p><code>[btn setTitle:@&quot;xxx&quot; forState:UIControlEventTouchUpInside];</code> </p>
<h3 id="Init-和-类构造方法"><a href="#Init-和-类构造方法" class="headerlink" title="Init 和 类构造方法"></a>Init 和 类构造方法</h3><figure class="highlight swift"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">- (instancetype)<span class="keyword">init</span> </div><div class="line">&#123;  </div><div class="line">  <span class="keyword">if</span> (<span class="keyword">self</span> = [<span class="keyword">super</span> <span class="keyword">init</span>]) &#123;  </div><div class="line">    <span class="comment">// ...  </span></div><div class="line">  &#125;  </div><div class="line">  <span class="keyword">return</span> <span class="keyword">self</span>;  </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>当类构造方法被使用时，它应该返回类型是 instancetype 而不是 id，这样确保编译器正确地推断结果类型。</p>
<figure class="highlight elm"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">@interface <span class="type">Airplane</span>  </div><div class="line">+ (instance<span class="keyword">type</span>)airplaneWithTestType:(<span class="type">DKTestType</span>)<span class="keyword">type</span>;  </div><div class="line">@end</div></pre></td></tr></table></figure>
<h3 id="RAC规范"><a href="#RAC规范" class="headerlink" title="RAC规范"></a>RAC规范</h3><p>在使用 RAC 的方法的前一行要写<code>@weakify(self);</code> 在 RAC 方法回调中的第一行写 <code>@strongify(self);</code> weakify 和 strongify 一定是成双存在，weakify 在一个方法的作用域内只能写一次；而 strongify 在每个 RAC 的 block 回调中都要写一次，嵌套时只需要在最外层写一次。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">@weakify(<span class="keyword">self</span>);</div><div class="line">[[<span class="keyword">self</span>.loadMoreBtn rac_signalForControlEvents:<span class="built_in">UIControlEventTouchUpInside</span>] subscribeNext:^(<span class="keyword">id</span> x) &#123;</div><div class="line">    @strongify(<span class="keyword">self</span>);</div><div class="line">    [DKProgressHUD showLoadingToView:<span class="keyword">self</span>.view];</div><div class="line">    [[<span class="keyword">self</span>.vm.loadWeekNewsCommand execute:@(++page)] subscribeNext:^(<span class="keyword">id</span> x) &#123;</div><div class="line">        <span class="comment">// ... 此处的 block 不需要写 strongify</span></div><div class="line">    &#125; error:^(<span class="built_in">NSError</span> *error) &#123;</div><div class="line">        @strongify(<span class="keyword">self</span>);</div><div class="line">        <span class="comment">// ...</span></div><div class="line">    &#125;];</div><div class="line">&#125;];</div></pre></td></tr></table></figure>
<p>注意，跟 RAC 相关的对象，都要用 <code>self.xxx</code> 的方式去调用，不要写成变量，也不要用下划线去调用<code>_xxx</code>，否则会导致循环引用引起控制器被强引用，最明显的结果就是不走 dealloc 方法，会导致很多问题，比如 RAC 重复绑定数据引起程序奔溃等。</p>
<p>在 viewModel 中定义 RACCommand 时，一定要写 <code>[subscriber sendCompleted];</code> 否则会阻塞 UI 主线程，导致 command 只能 execute 一次。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">@weakify(<span class="keyword">self</span>);</div><div class="line">_loadOldDataCommand = [[DKCommand alloc] initWithSignalBlock:^RACSignal *(<span class="keyword">id</span> input) &#123;</div><div class="line">    <span class="keyword">return</span> [RACSignal createSignal:^RACDisposable *(<span class="keyword">id</span>&lt;RACSubscriber&gt; subscriber) &#123;</div><div class="line">        @strongify(<span class="keyword">self</span>);</div><div class="line">        <span class="keyword">self</span>.items = DKGetCache(KITEM);</div><div class="line">        [subscriber sendNext:<span class="literal">nil</span>];</div><div class="line">        [subscriber sendCompleted];</div><div class="line">        <span class="keyword">return</span> <span class="literal">nil</span>;</div><div class="line">    &#125;];</div><div class="line">&#125;];</div></pre></td></tr></table></figure>
<h2 id="命名规范"><a href="#命名规范" class="headerlink" title="命名规范"></a>命名规范</h2><h3 id="命名原则"><a href="#命名原则" class="headerlink" title="命名原则"></a>命名原则</h3><ul>
<li><p>一般性原则：</p>
<ul>
<li><p>可读性高(简洁且清晰)和防止命名冲突(通过加前缀后缀来保证)。</p>
</li>
<li><p>Objective-C 的命名通常都比较长, 名称遵循驼峰式命名法. 一个好的命名标准很简单, 就是做到在开发者一看到名字时, 就能够懂得它的含义和使用方法. 另外, 每个模块都要加上自己的前缀, 前缀在编程接口中非常重要, 可以区分软件的功能范畴并防止不同文件或者类之间命名发生冲突, 比如 DKTableView、DKDataBase</p>
</li>
</ul>
</li>
</ul>
<table>
<thead>
<tr>
<th>代码</th>
<th>是否正确规范</th>
</tr>
</thead>
<tbody>
<tr>
<td>insertObject:atIndex:</td>
<td>正确 </td>
</tr>
<tr>
<td>insert:at:</td>
<td>不清晰，没有说明插入什么，插到哪里  </td>
</tr>
<tr>
<td>removeObjectAtIndex:</td>
<td>正确 </td>
</tr>
<tr>
<td>removeObject:</td>
<td>正确，因为⽅法是⽤来移除作为参数的对象</td>
</tr>
<tr>
<td>remove:</td>
<td>不清晰，没有说明要移除什么</td>
</tr>
</tbody>
</table>
<ul>
<li><p>一致性</p>
<p>  尽可能与 Cocoa 编程接⼝命名保持一致。如果不太确定某个命名的⼀致性，请浏览头文件或参考文档中的范例，在使⽤多态方法的类中，命名的⼀致性⾮常重要。在不同类中实现相同功能的⽅法应该具有同的名称。</p>
</li>
</ul>
<table>
<thead>
<tr>
<th>代码</th>
<th>点评 </th>
</tr>
</thead>
<tbody>
<tr>
<td>– (NSInteger)tag</td>
<td>在 NSView, NSCell, NSControl 中有定义</td>
</tr>
<tr>
<td>– (void)setStringValue:(NSString *)</td>
<td>在许多 Cocoa classes 中都有定义 </td>
</tr>
</tbody>
</table>
<h3 id="文件命名"><a href="#文件命名" class="headerlink" title="文件命名"></a>文件命名</h3><p>文件的扩展名应该如下:</p>
<table>
<thead>
<tr>
<th>文件名规范</th>
<th>文件类型</th>
</tr>
</thead>
<tbody>
<tr>
<td>.h</td>
<td>C / C++ / Objective-C 头文件</td>
</tr>
<tr>
<td>.m</td>
<td>Objective-C 实现文件</td>
</tr>
<tr>
<td>.mm</td>
<td>Objective-C / C++ 实现文件</td>
</tr>
<tr>
<td>.cc</td>
<td>纯 C++ 实现文件</td>
</tr>
<tr>
<td>.c</td>
<td>纯 C 实现文件</td>
</tr>
</tbody>
</table>
<p>分类的文件名应该包含被扩展的类名，如：NSString+DKUtils.h 或 NSTextView+DKAutocomplete.h。</p>
<h3 id="编码命名"><a href="#编码命名" class="headerlink" title="编码命名"></a>编码命名</h3><h4 id="类的命名"><a href="#类的命名" class="headerlink" title="类的命名"></a>类的命名</h4><ul>
<li><p>类名（以及类别、协议名）应首字母大写，并以驼峰格式分割单词。</p>
</li>
<li><p>所有类名、枚举、结构、protocol定义时最好加一个统一的标示符，可以是项目缩写，或者个人项目的名称缩写，目前规定都加上大写的<code>DK</code>作为根前缀。</p>
</li>
<li><p>根据功能模块可以给功能模块的类添加功能模块的名称前缀，如用户中心的控制器，属于<code>Profile</code>模块，可以命名为 <code>DKProfileViewController</code>。</p>
</li>
</ul>
<h4 id="声明定义"><a href="#声明定义" class="headerlink" title="声明定义"></a>声明定义</h4><ul>
<li><p>所有 protocol 定义时，都加上后缀 Delegate。</p>
<p> 比如 <code>DKRefreshViewDelegate</code>，表示<code>RefreshView</code>的协议</p>
</li>
<li><p>所有的通知名都加上Notification，通知名格式为：</p>
<p> <code>[ 触发通知的类名 ] + [Did/Will] + [ 动作 ] + Notification</code></p>
<p> 例如</p>
 <figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">NSWindowDidMiniaturizeNotification</span></div><div class="line"><span class="built_in">NSTextViewDidChangeSelectionNotification</span></div><div class="line"><span class="built_in">NSColorPanelColorDidChangeNotification</span></div></pre></td></tr></table></figure>
</li>
</ul>
<h4 id="方法命名"><a href="#方法命名" class="headerlink" title="方法命名"></a>方法命名</h4><ul>
<li><p>小驼峰原则</p>
<p>  方法名应遵守小驼峰原则首字母小写，其他单词首字母大写,每个空格分割的名称以动词开头。执行性的方法应该以动词开头，小写字母开头，返回性的方法应该以返回的内容开头，但之前不要加get。</p>
</li>
</ul>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">void</span>)insertModel:(<span class="keyword">id</span>)model atIndex:(<span class="built_in">NSUInteger</span>)atIndex;</div><div class="line"></div><div class="line">- (<span class="keyword">instancetype</span>)arrayWithArray:(<span class="built_in">NSArray</span> *)array;</div></pre></td></tr></table></figure>
<ul>
<li><p>代理方法</p>
<p>  以发送代理的对象类名作为代理方法名的开始（去掉类名的前缀，并且小写开头）</p>
</li>
</ul>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">- (<span class="built_in">BOOL</span>)tableView:(<span class="built_in">NSTableView</span> *)tableView shouldSelectRow:(<span class="keyword">int</span>)row;</div><div class="line">	</div><div class="line">- (<span class="built_in">BOOL</span>)application:(<span class="built_in">NSApplication</span> *)sender openFile:(<span class="built_in">NSString</span> *)filename;</div></pre></td></tr></table></figure>
<h4 id="枚举命名"><a href="#枚举命名" class="headerlink" title="枚举命名"></a>枚举命名</h4><figure class="highlight elm"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">typedef <span class="type">NS_ENUM</span>(<span class="type">NSInteger</span>, <span class="type">DKGlobalConstants</span>) &#123;  </div><div class="line">   <span class="type">DKPinSizeMin</span> = 1,  </div><div class="line">   <span class="type">DKPinSizeMax</span> = 5,  </div><div class="line">   <span class="type">DKPinCountMin</span> = 100,  </div><div class="line">   <span class="type">DKPinCountMax</span> = 500,  </div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<p>不使用下面这种方式</p>
<figure class="highlight crystal"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">enum</span> <span class="title">GlobalConstants</span> &#123;  </span></div><div class="line">   kMaxPinSize = <span class="number">5</span>,  </div><div class="line">   kMaxPinCount = <span class="number">500</span>,  </div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<h4 id="宏命名"><a href="#宏命名" class="headerlink" title="宏命名"></a>宏命名</h4><p>以大写K开头，后面单词首字母大写，其余小写。如：<code>#define KMaxHeigt 100.0</code></p>
<h4 id="属性变量命名"><a href="#属性变量命名" class="headerlink" title="属性变量命名"></a>属性变量命名</h4><p>变量名使用小驼峰法, 使变量名尽量可以推测其用途属性具有描述性。别一心想着少打几个字母，让你的代码可以迅速被理解更加重要。</p>
<p>每个属性命名都加上类型后缀，如按钮就加上<code>btn</code>后缀，imageView 就加上<code>imgView</code>。</p>
<p>如果是布尔值的成员变量，要定义 getter 方法 为 isXXX</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>, <span class="keyword">assign</span>, <span class="keyword">getter</span>=isEditable) <span class="built_in">BOOL</span> editable;</div></pre></td></tr></table></figure>
<table>
<thead>
<tr>
<th>标题</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>类成员变量名</td>
<td>成员变量用小驼峰法命名并前缀下划线</td>
</tr>
<tr>
<td>局部变量名</td>
<td>遵守小驼峰命名规则</td>
</tr>
<tr>
<td>const常量</td>
<td>以小写 k 开头，后面单词首字母大写</td>
</tr>
</tbody>
</table>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <ul class="post-copyright">
    <li class="post-copyright-author">
      <strong>本文作者：</strong>
      Bingo
    </li>
    <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://bingozb.github.io/27.html" title="iOS开发编码规范">https://bingozb.github.io/27.html</a>
    </li>
    <li class="post-copyright-license">
      <strong>版权声明： </strong>
      本博客所有文章除特别声明外，均采用 MIT 许可协议。转载请注明出处！
    </li>
  </ul>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/iOS/" rel="tag"># iOS</a>
          
            <a href="/tags/Android/" rel="tag"># Android</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/28.html" rel="next" title="Centos 6 x86 minimal 部署">
                <i class="fa fa-chevron-left"></i> Centos 6 x86 minimal 部署
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/26.html" rel="prev" title="DKSocketLog 实现终端输出设备日志">
                DKSocketLog 实现终端输出设备日志 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="Bingo" />
          <p class="site-author-name" itemprop="name">Bingo</p>
           
              <p class="site-description motion-element" itemprop="description">He who hesitates is lost.</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">55</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">22</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/bingozb" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://coding.net/u/bingozb" target="_blank" title="Coding">
                  
                    <i class="fa fa-fw fa-git"></i>
                  
                  Coding
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/bingo_v587" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.facebook.com/profile.php?id=100013406670597" target="_blank" title="Facebook">
                  
                    <i class="fa fa-fw fa-facebook"></i>
                  
                  Facebook
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#代码规范"><span class="nav-number">1.</span> <span class="nav-text">代码规范</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#头文件"><span class="nav-number">1.1.</span> <span class="nav-text">头文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#类结构"><span class="nav-number">1.2.</span> <span class="nav-text">类结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Private-Methods"><span class="nav-number">1.3.</span> <span class="nav-text">Private Methods</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#懒加载"><span class="nav-number">1.4.</span> <span class="nav-text">懒加载</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#空格"><span class="nav-number">1.5.</span> <span class="nav-text">空格</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#方法书写"><span class="nav-number">1.6.</span> <span class="nav-text">方法书写</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#方法调用"><span class="nav-number">1.7.</span> <span class="nav-text">方法调用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#if-语句"><span class="nav-number">1.8.</span> <span class="nav-text">if 语句</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#switch-语句"><span class="nav-number">1.9.</span> <span class="nav-text">switch 语句</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#注释"><span class="nav-number">1.10.</span> <span class="nav-text">注释</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#点语法"><span class="nav-number">1.11.</span> <span class="nav-text">点语法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Init-和-类构造方法"><span class="nav-number">1.12.</span> <span class="nav-text">Init 和 类构造方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#RAC规范"><span class="nav-number">1.13.</span> <span class="nav-text">RAC规范</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#命名规范"><span class="nav-number">2.</span> <span class="nav-text">命名规范</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#命名原则"><span class="nav-number">2.1.</span> <span class="nav-text">命名原则</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#文件命名"><span class="nav-number">2.2.</span> <span class="nav-text">文件命名</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#编码命名"><span class="nav-number">2.3.</span> <span class="nav-text">编码命名</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#类的命名"><span class="nav-number">2.3.1.</span> <span class="nav-text">类的命名</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#声明定义"><span class="nav-number">2.3.2.</span> <span class="nav-text">声明定义</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#方法命名"><span class="nav-number">2.3.3.</span> <span class="nav-text">方法命名</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#枚举命名"><span class="nav-number">2.3.4.</span> <span class="nav-text">枚举命名</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#宏命名"><span class="nav-number">2.3.5.</span> <span class="nav-text">宏命名</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#属性变量命名"><span class="nav-number">2.3.6.</span> <span class="nav-text">属性变量命名</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  Copyright © 
  <span itemprop="copyrightYear">2017
  </span>
  <span class="author" itemprop="copyrightHolder">Bingo
  </span>
  All rights reserved.
</div>
        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cytcdzpa3';
      var conf = 'c0c6117021d1cea9f11629100efd8446';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (search_path.endsWith("json")) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      $('#local-search-input').focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('-1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("A9MeTkIR49W9kOOSvkggsXge-gzGzoHsz", "HaIEOSDyxpcjwOjRjCYxiWjA");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  

</body>
</html>
